package com.brspace.qualitycontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brspace.qualitycontrol.entity.*;
import com.brspace.qualitycontrol.entity.vo.LetterListVo;
import com.brspace.qualitycontrol.entity.vo.PersonalListVo;
import com.brspace.qualitycontrol.mapper.UserMapper;
import com.brspace.qualitycontrol.repository.UserRepository;
import com.brspace.qualitycontrol.service.*;
import com.brspace.qualitycontrol.utils.EmptyUtil;
import com.brspace.qualitycontrol.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-04-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private LeaveService leaveService;
    @Resource
    private MeetApplyService meetApplyService;
    @Resource
    private LetterService letterService;
    @Resource
    private CollectWritService collectWritService;
    @Resource
    private PublishService publishService;
    @Override
    public User findByName(String username) {
        return userMapper.findByName(username);
    }
    /**
     * 人事代办
     * @Author wangt
     * @Date 2021-05-07 14:31:10
     */
    @Override
    public R findAll(int page,int limit,String id) {
        List<PersonalListVo> list = new ArrayList<>();
        // 人事台账，请假/或加班
        R page1 = leaveService.selectPage1(page, limit, null, id);
        Object rows = page1.getData().get("rows");
        List<Leaveing> list01 = castList(rows, Leaveing.class);
        for (Leaveing leaveing : list01) {
            System.err.println("--------------------------******************-------------------------"+leaveing);
            PersonalListVo personalListVo = new PersonalListVo();
            personalListVo.setId(leaveing.getId());
            personalListVo.setTypes(5);
            personalListVo.setTitle(leaveing.getTitle());
            personalListVo.setTimes(leaveing.getCreateTime());
            list.add(personalListVo);
        }
        // 三重一大
        R page01 = meetApplyService.selectPage01(page, limit, id);
        Object rows01 = page01.getData().get("rows");
        List<MeetApply> list02 = castList(rows01, MeetApply.class);
        for (MeetApply apply : list02) {
            System.err.println("---------------------------****************-------------------------"+apply);
            PersonalListVo personalListVo = new PersonalListVo();
            personalListVo.setId(apply.getId());
            personalListVo.setTypes(1);
            personalListVo.setTitle(apply.getMeetingType());
            personalListVo.setTimes(apply.getCreateTime());
            list.add(personalListVo);
        }
        // 信访诉求（来信、领导信箱，网信）
        R selectPage1 = letterService.findList(page, limit, null, id);
        Object rows1 = selectPage1.getData().get("rows");
        List<LetterListVo> letters = castList(rows1, LetterListVo.class);
        for (LetterListVo letter : letters) {
            System.err.println("---------------------------****************-------------------------"+letter);
            PersonalListVo personalListVo = new PersonalListVo();
            personalListVo.setId(letter.getId());
            personalListVo.setTypes(3);
            personalListVo.setTitle(letter.getTitle());
            personalListVo.setTimes(letter.getTimes());
            list.add(personalListVo);
        }
        // 收文
        List<CollectWrit> collectWrits = collectWritService.pageUnCompleteList(page, limit, id);
        for (CollectWrit writ : collectWrits) {
            System.err.println("---------------------------****************-------------------------"+writ);
            PersonalListVo personalListVo = new PersonalListVo();
            personalListVo.setId(writ.getId());
            personalListVo.setTypes(6);
            personalListVo.setTitle(writ.getTitle());
            personalListVo.setTimes(writ.getCreateTime());
            personalListVo.setNumber(writ.getWritNum());
            personalListVo.setSource(writ.getComeUnit());
            list.add(personalListVo);
        }
        // 发文
        List<Publish> publishes = publishService.pageList(page, limit, id);
        for (Publish publish : publishes) {
            System.err.println("---------------------------****************-------------------------"+publish);
            PersonalListVo personalListVo = new PersonalListVo();
            personalListVo.setId(publish.getId());
            personalListVo.setTypes(7);
            personalListVo.setTitle(publish.getTitle());
            personalListVo.setTimes(publish.getCreateTime());
            personalListVo.setNumber(publish.getWordNumber());
            personalListVo.setSource(publish.getOrganizer());
            list.add(personalListVo);
        }
        return R.ok().data("rows",page(list,limit, page)).data("total",list.size());
    }

    public static List<PersonalListVo> page(List<PersonalListVo> dataList, int pageSize, int currentPage) {
        List<PersonalListVo> currentPageList = new ArrayList<>();
        if (dataList != null && dataList.size() > 0) {
            int currIdx = (currentPage > 1 ? (currentPage - 1) * pageSize : 0);
            for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
                currentPageList.add(dataList.get(currIdx + i));
            }
        }
        return currentPageList;
    }

    /**
     *用户注册
     *@author Hugo
     *@date 2021-04-15 15:44
     **/
    @Override
    public void saveInfo(User user) {
        this.check(user);
        baseMapper.insert(user);
    }

    /**
     *用户登录
     *@author Hugo
     *@date 2021-04-16 18:01
     **/
    @Override
    public User login(User user) {
        if (baseMapper.selectCount(new QueryWrapper<User>().eq("username",user.getUsername())) == 0){
            throw new SecurityException("用户名不存在");
        }
        if (!baseMapper.selectOne(new QueryWrapper<User>().eq("username",user.getUsername())).getPassword().equals(user.getPassword())){
            throw new SecurityException("用户名密码错误");
        }
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username",user.getUsername()));
    }
    /**
     * 用户分页查询
     * @Author: wangt
     * @Date: 2021-04-21 14:35:34
     */
    @Override
    public IPage<User> selectPage(Page<User> pageParam, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user==null){
            return baseMapper.selectPage(pageParam,queryWrapper);
        }
        if (!EmptyUtil.isEmpty(user.getName())) {
            queryWrapper.eq("name",user.getName());
        }
        return baseMapper.selectPage(pageParam,queryWrapper);
    }

    @Override
    public UserRepository getRepository() {
        return null;
    }



    public void check(User user){
        if ("".equals(user.getName())){
            throw  new SecurityException("姓名不能为空");
        }
        if("".equals(user.getPassword())){
            throw new SecurityException("用户密码不能为空");
        }
        if ("".equals(user.getUsername())){
            throw new SecurityException("用户昵称不能为空");
        }
        if (baseMapper.selectCount(new QueryWrapper<User>().eq("username",user.getUsername()))>0){
            throw new SecurityException("用户名称不能重复");
        }
    }

    public static <T> List<T> castList(Object obj, Class<T> clazz)
    {
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>)
        {
            for (Object o : (List<?>) obj)
            {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
}
